<template>
  <el-container>
    <el-header
      style="100px;width:78%;padding-left:200px;padding-top:10px;margin:auto;margin-top:100px"
    >
      <!-- <el-button
        type="success"
        round
        style="width: 150px; margin-left: 50px"
        icon="el-icon-edit"
        >编辑</el-button
      >
      <el-button
        type="danger"
        round
        style="width: 150px; margin-left: 50px"
        icon="el-icon-delete"
        >删除</el-button
      > -->
    </el-header>
    <el-main>
      <el-tabs
        stretch
        type="border-card"
        style="width: 80%; height: 80%; margin: auto"
      >
        <el-tab-pane label="部门管理">
          <el-table
            :data="
              deptList.slice(
                (currentPage - 1) * pageSize,
                currentPage * pageSize
              )
            "
            id="table"
            style="width: 100%"
            row-key="deptId"
            height="500px"
            border
            @selection-change="handleSelectionChange"
            lazy
            :load="load"
            :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
          >
            <el-table-column type="selection" width="55" align="center"> </el-table-column>
            <el-table-column prop="deptId" label="部门ID" width="180" align="center">
            </el-table-column>
            <el-table-column prop="name" label="部门名称" align="center" width="280">
            </el-table-column>
            <!-- <el-table-column prop="parentName" align="center" label="上级部门">
            </el-table-column> -->
            <el-table-column prop="delFlag" label="排序号" align="center"> </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  style="margin-left: 50px"
                  icon="el-icon-edit"
                  @click="getInfo(scope.row.deptId)"
                  circle
                ></el-button>
                <el-button
                  type="danger"
                  style="margin-left: 10px"
                  @click="deleteDept(scope.row.deptId)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            alian="center"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="deptList.length"
            background="true"
            style="margin-left: 800px"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane
          label="新增部门"
          style="padding-left: 150px; padding-top: 50px"
        >
          <el-form
            ref="form"
            :model="add"
            label-width="100px"
            label-position="right"
          >
            <el-form-item label="部门名称：" required="true">
              <el-input
                v-model="add.name"
                style="width: 300px"
                placeholder="请输入新部门的名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="上级部门：" required="true">
              <el-input
                v-model="add.parentName"
                id="parentdept"
                style="width: 300px"
                placeholder="请选择上级部门"
                @focus="openParentDept()"
              ></el-input>
            </el-form-item>
            <el-form-item label="排序号：" required="true">
              <el-input
                v-model="add.orderNum"
                style="width: 300px"
                placeholder="请输入新部门的排序号"
              ></el-input>
            </el-form-item>
            <el-form-item label="部门经理：" required="true">
              <el-input
                v-model="add.manger"
                style="width: 300px"
                placeholder="请输入新部门的负责人"
              ></el-input>
            </el-form-item>
            <el-form-item label="设立时间：" required="true">
              <el-date-picker
                v-model="add.date"
                type="date"
                placeholder="选择部门设立日期"
              >
              </el-date-picker>
            </el-form-item>
            <div style="margin-left: 270px; margin-top: 150px">
              <el-button
                type="primary"
                round
                icon="el-icon-check"
                style="width: 200px; margin-right: 50px"
                @click="submitAdd()"
                >提交</el-button
              >
              <el-button type="warning" round style="width: 200px"
                >撤销</el-button
              >
            </div>
          </el-form>
          <div id="newtips">
            <h2 style="text-align: center; line-height: 50px">提示</h2>
            <span style="font-size: 18px; line-height: 50px"
              >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在开设新部门时，请在左侧的表单中认真填写新部门的基本信息其中，带<strong
                style="color: red"
                >*</strong
              >号的为必填项，请核对正确信息后再进行填写，上级部门即为该新部门的主管部门，如该部门出现了问题，请联系上级部门。</span
            >
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        title="选择上级部门"
        :visible.sync="dialogVisible"
        modal
        width="40%"
        center
        :before-close="handleClose"
      >
        <el-tree
          :data="deptList"
          :props="defaultProps"
          @node-click="handleNodeClick"
          accordion
        >
        </el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="selectParentDept()"
            >确 定</el-button
          >
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-dialog title="部门修改" width="40%" :visible.sync="dialogFormVisible2" center >
        <el-form :model="modify" label-width="150px" label-position="right"> 
          <el-form-item required="true" label="原部门名：">
            <el-input v-model="oldName" disabled></el-input>
          </el-form-item>
          <el-form-item required="true" label="新的部门名：">
            <el-input v-model="modify.name" ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="modifyDept()"
            >确 定</el-button
          >
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>
<script>
import api from "@/api/department";
export default {
  data() {
    return {
      deptList: [],
      selection: [],
      defaultProps: {
        children: "childrens",
        label: "name",
      },
      add: {
        name: "",
        parentName: "",
        parentId: "",
        date: "",
        manger: "",
        orderNum: "",
      },
      modify:{
        deptId:'',
        parentId:'',
        name:'',
        parentName:'',
        orderNum:'',
        delFlag:'',
        companyId:'',
        open:'',
        list:''
      },
      //当前页数
      currentPage: 1,
      //一页几条数据
      pageSize: 10,
      //选中的上级部门
      parentDept: "",
      dialogVisible: false,
      oldName:'',
      dialogFormVisible2: false,
    };
  },
  methods: {
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve(this.deptList[0].childrens);
      }, 200);
    },
    cmp(a, b) {
      return a.parentId < b.parentId;
    },
    //节点选中状态
    handleNodeClick(data) {
      this.parentDept = data;
      this.add.parentName = data.name;
      this.add.parentId = data.deptId;
    },
    //获取部门列表
    getDeptList() {
      api
        .getDeptList()
        .then((response) => {
          let list = response.list;
          let deps = [];
          let ds = [];
          for (let index = 0; index < list.length; index++) {
            list[index].childrens = [];
            deps.push(list[index]);
          }
          deps.sort(this.cmp);
          for (let index = 0; index < deps.length; index++) {
            const element = deps[index];
            for (let index2 = 0; index2 < deps.length; index2++) {
              const element = deps[index2];
              element.delFlag=index2
              if (deps[index2].parentId == deps[index].deptId) {
                deps[index].childrens.push(deps[index2]);
              }
            }
            if (deps[index].childrens.length != 0) {
              ds.push(deps[index]);
            }
            if (deps[index].parentId==0) {
              ds.push(deps[index])
            }
          }
          this.deptList.push(ds[0]);
          let s = JSON.stringify(this.deptList);
          console.log(this.deptList);
        })
        .catch((err) => {
          this.$message.error("网络异常。请检查设置");
        });
    },
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    //打开选择上级部门列表
    openParentDept() {
      this.dialogVisible = true;
    },
    //确定选择上级部门
    selectParentDept() {
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        message: "已选择新部门的上级部门为：" + this.parentDept.name,
        type: "success",
      });
    },
    //提交新部门的表单
    submitAdd() {
      this.$confirm("是否提及新部门的信息", "提交", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api
            .addDept(this.add)
            .then((response) => {
              this.$message({
                type: "success",
                message: "提交成功",
              });
              setTimeout(() => {
                this.$router.go(0);
              }, 300);
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: "网络出错",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消提交",
          });
        });
    },
    //删除部门
    deleteDept(data) {
      this.$confirm("此操作将永久删除该部门", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api
            .deleteDept(data)
            .then((response) => {
              this.$notify({
                title: "成功",
                message: "已成功删除部门",
                type: "success",
              });
              setTimeout(() => {
                this.$router.go(0);
              }, 300);
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: "网络出错",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改部门信息
    modifyDept() {
      if (this.oldName!=this.modify.name) {
           this.$confirm('确定将此'+this.oldName+'的名字更改为'+this.modify.name+'吗？', '提示', {
          cancelButtonText: '取消',
            confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          api.modify(this.modify).then(response=>{
                this.$notify({
          title: '成功',
          message: '修过部门名称成功',
          type: 'success'
        });
        this.dialogFormVisible2=false
        setTimeout(() => {
          this.$router.go(0)
        }, 300);
          }).catch(err=>{
            this.$message.error('网络错误');
          })
       
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          }); 
        })      
      }
    },
    //获取选中部门的部门信息
    getInfo(data){
      api.getInfo(data).then(response=>{
        this.modify=response.dept
        this.oldName=response.dept.name
         this.dialogFormVisible2 = true;
      }).catch(err=>console.log(err))
    }
  },
  created() {
    this.getDeptList();
  },
};
</script>
 <style  >
.el-container {
  /*height: 100%; 可以固定头部*/
  /*height: auto; 头部会跟随滚动*/
  height: 1000px;
  /* background-color: rgb(173, 173, 173); */
}
#table {
  margin: auto;
  /* margin-top: 200px; */
}
#parentdept {
  cursor: pointer;
}
#parentdept:hover {
  border: 2px solid skyblue;
}
#newtips {
  width: 450px;
  padding: 10px;
  height: 350px;
  background-image: linear-gradient(to right, rgba(255, 253, 253, 0), skyblue);
  position: absolute;
  top: 80px;
  right: 100px;
}
</style>